package com.ljfiction.book.tools;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.util.Log;
import android.view.View;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
 * Created by dell on 2017/9/12.
 */

public class BitmapUtils {
  public static Bitmap compressImage(Bitmap image) {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
    int options = 100;
    Log.e("size3", "//" + baos.toByteArray().length / 1024);
    while (baos.toByteArray().length / 1024 > 80) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
      baos.reset();//重置baos即清空baos
      //第一个参数 ：图片格式 ，第二个参数： 图片质量，100为最高，0为最差  ，第三个参数：保存压缩后的数据的流
      image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
      options -= 10;//每次都减少10
    }
    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
    Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, getBitmapOption(2));//把ByteArrayInputStream数据生成图片
    Log.e("size2", "//" + (bitmap.getRowBytes() * bitmap.getHeight()));
    return bitmap;
  }

  public static BitmapFactory.Options getBitmapOption(int inSampleSize) {

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Bitmap.Config.RGB_565;
    options.inPurgeable = true;
    options.inSampleSize = inSampleSize;
    options.inJustDecodeBounds = false;
    return options;
  }

/*  @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
  public static void ViewSetBitmap(Resources res, int id, View view,int inSampleSize) {
    try {

      Bitmap bmp = BitmapFactory.decodeResource(res, id, getBitmapOption(inSampleSize));
      if (!bmp.isRecycled()) {
        view.setBackground(new BitmapDrawable(bmp));
//        bmp.recycle();
      }

    } catch (OutOfMemoryError err) {
    }
  }

  @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
  public static Bitmap ViewSetBitmap(Resources res, int id) {
    try {

      Bitmap bmp = BitmapFactory.decodeResource(res, id, getBitmapOption(2));
      if (!bmp.isRecycled()) {
        return bmp;
      }

    } catch (OutOfMemoryError err) {
    }
    return null;
  }*/
}
